#校验jwt值(token)
import base64
import hashlib
import json
import sys
import time

if __name__ == '__main__':
   #  """头部生成原理"""
   #  header_dict = {
   #      "typ": "JWT",
   #      "alg": 'HS256',
   #  }
   #  # 把字典转换成json
   #  import json
   #  header_json = json.dumps(header_dict)
   # # print(header_json)
   #  # 把json使用base64编码
   #  import base64
   #  header = base64.b64encode(header_json.encode()).decode()
   # # print(header)
   #
   #
   #  """载荷的生成原理"""
   #  import time
   #  iat = int(time.time())
   #  payload_dict = {
   #      "sub": "root",
   #      "exp": iat + 3600,  # 假设一小时过期
   #      "iat": iat,
   #      "name": "zhangsan",
   #      "avatar": "uploads/avatar/2022/1.png",
   #      "user_id": 1,
   #      "admin": True,
   #      "acc_pwd": "QiLCJhbGciOiJIUzI1NiJ9QiLCJhbGciOiJIUzI1NiJ9QiLCJhbGciOiJIUzI1NiJ9",
   #  }
   #
   #  # 把字典转换成json
   #  payload_json = json.dumps(payload_dict)
   # # print(payload_json)
   #
   #  # 将其进行base64编码，得到JWT的第二部分。
   #  payload = base64.b64encode(payload_json.encode()).decode()
   # # print(payload)
   #
   #
   #  """签证的生成原理"""
   #  import hashlib
   #  # from django.conf import settings
   #  # secret = settings.SECRET_KEY
   #  secret = 'django-insecure-p$rk-@07vu50f_f!7b!w4gcd!&!7)$owed-by$tgncfl7u!2*j'
   #
   #  raw_signature = header + payload + secret  # 秘钥绝对不能提供给客户端。
   #  HS256 = hashlib.sha256()
   #  HS256.update(raw_signature.encode('utf-8'))
   #  signature = HS256.hexdigest()
   #  #print(signature)
   #
   #  # jwt 最终的生成
   #  token = f"{header}.{payload}.{signature}"
   #  print(token)


    # """认证环节"""
    # 模拟客户端提交的token
    token = "eyJ0eXAiOwwwwiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9.eyJzdWIiOiAicm9vdCIsICJleHAiOiAxNzQzNTU5NDA1LCAiaWF0IjogMTc0MzU1NTgwNSwgIm5hbWUiOiAiemhhbmdzYW4iLCAiYXZhdGFyIjogInVwbG9hZHMvYXZhdGFyLzIwMjIvMS5wbmciLCAidXNlcl9pZCI6IDEsICJhZG1pbiI6IHRydWUsICJhY2NfcHdkIjogIlFpTENKaGJHY2lPaUpJVXpJMU5pSjlRaUxDSmhiR2NpT2lKSVV6STFOaUo5UWlMQ0poYkdjaU9pSklVekkxTmlKOSJ9.951b63430cf9e5f0d001eb8cf8158bc4bba312e707dd29aaca35fea0fb98e11d"
    # 把客户端提交的token分割成三段：头部、载荷、签证
    header, payload, signature = token.split(".")
    # 验证是否过期了
    # 先基于base64，接着使用json解码
    payload_data = json.loads(base64.b64decode(payload.encode()))

    exp = payload_data.get("exp", None)
    now = int(time.time())
    if exp is None or exp < now:
        print("token已经过期!")
        sys.exit() # 退出程序，实际开发中，应该时响应代码给客户端，不会继续往下执行了。
    else:
        print("token没有过期！")

    # 验证token是否有效，是否被篡改
    secret = 'django-insecure-p$rk-@07vu50f_f!7b!w4gcd!&!7)$owed-by$tgncfl7u!2*j'
    raw_signature = header + payload + secret  # 秘钥绝对不能提供给客户端。
    HS256 = hashlib.sha256()
    HS256.update(raw_signature.encode('utf-8'))
    new_signature = HS256.hexdigest()
    if new_signature != signature:
        print("认证失败，token被串改！")
    else:
        print("认证通过")
